'use strict';
const jwt = require('jwt-simple');
const crypto = require('crypto');
const db = uniCloud.database();
const loginConfig = {
	appid: 'wx27887374bd5948da',
	secret: '6025e90ebaf5bde7c598e216eff44699'
}
exports.main = async (event, context) => {
	// 封装数据
	let data = {
		appid: loginConfig.appid,
		secret: loginConfig.secret,
		js_code: event.code,
		grant_type: 'authorization_code'
	}
	// 向微信服务器提交code+appid+secret，返回openId和session-key
	const JSCODE_ESSION_URL = 'https://api.weixin.qq.com/sns/jscode2session'
	const res = await uniCloud.httpclient.request(JSCODE_ESSION_URL,{
		method: 'GET',
		data,
		dataType: 'json'
	})
	
	const success = res.status === 200 && res.data && res.data.openid
	if(!success) {
		return {
			status: -1,
			msg: '微信登录失败'
		}
	}
	
	let openId = res.data.openid
	const tokenExp = 7200000
	
	let time = Date.now()
	let tokenSecret = crypto.randomBytes(16).toString('hex'),
	    token = jwt.encode(openId, tokenSecret)
		
	let userInfo = {
		openId: res.data.openid,
		nickName: event.userInfo.nickName, 
		avatarUrl: event.userInfo.avatarUrl,
		gender: event.userInfo.gender,
		city: event.userInfo.city,
		balance: 0,
		couponNum: 0,
		currentValue: 0,
		needValue: 0,
		giftBalance: 0,
		level: '',
		pointNum: 0,
		CreateTime: time,
		lastLoginTime: time
	}
	
	let userUpdate = {
		openId: res.data.openid,
		nickName: event.userInfo.nickName,
		avatarUrl: event.userInfo.avatarUrl,
		gender: event.userInfo.gender,
		city: event.userInfo.city,
		lastLoginTime: time
	}
	
	let userResult
	
	const userInDB = await db.collection('users').where({openId}).limit(1).get();
	if(userInDB.data && userInDB.data.length === 0) {
		userResult = await db.collection('users').add({
			...userInfo,
			tokenSecret,
			exp: Date.now() + tokenExp
		})
	} else {
		userResult =  await db.collection('users').where({openId}).update({
			...userInfo,
			tokenSecret,
			exp: Date.now() + tokenExp
		})
	}
	
	//返回数据给客户端
	const fields = {
		nickName: 1,
		avatarUrl: 1,
		balance: 1,
		couponNum: 1,
		currentValue: 1,
		needValue: 1,
		giftBalance: 1,
		level: 1,
		pointNum: 1,
		gender: 1
	};
	
	let resultOk = await db.collection('users').where({openId}).field(fields).get();
	let resultData = resultOk.data[0]
	if(userResult.id || userResult.updated ===1){
		return {
			status: 0,
			msg: '登录成功',
			data: resultData,
			token:token
		}
	}else{
		return {
			status: -1,
			msg: '微信登录失败'
		}
	}
};
